package cn.liccshop.sys.config;

import cn.liccshop.core.entity.ShopOrderInfo;
import cn.liccshop.sys.cache.CommonCacheUtil;
import cn.liccshop.sys.constants.Constants;
import cn.liccshop.sys.entity.UserElement;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.reflection.wrapper.MapWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author LiCC
 * @program LiCCShop
 * @description 公共字段配置类
 * @since 2019-04-21-10:46
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private CommonCacheUtil commonCacheUtil;

    @Override
    public void insertFill(MetaObject metaObject) {
        /** 公共填充创建时间 **/
        setFieldValByName("createDate", LocalDateTime.now(), metaObject);
        /** 公共填充创建人 **/
        UserElement userElement = getUserInfoByToken();
        if (userElement!=null){
            setFieldValByName("createBy", userElement.getUserId(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        /** 公共填充更新时间 **/
        setFieldValByName("updateDate", LocalDateTime.now(), metaObject);
        /** 公共填充更新人 **/
        MapWrapper mapWrapper = (MapWrapper) metaObject.getObjectWrapper();
        Object et = (Object) mapWrapper.get(new PropertyTokenizer("et"));
        if (et instanceof ShopOrderInfo){
            System.out.println("=====>>>>>>AAAAAAAA");
        } else {
            UserElement userElement = getUserInfoByToken();
            if (userElement!=null){
                setFieldValByName("updateBy", userElement.getUserId(), metaObject);
            }
        }
    }
    /**
     * 通过该方法Controller可以获取用户信息
     * @return
     */
    protected UserElement getUserInfoByToken(){
        HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = servletRequest.getHeader(Constants.REQUEST_TOKEN_KEY);
        UserElement userElement = null;
        if (!StringUtils.isBlank(token)){
            try {
                userElement = commonCacheUtil.getUserElementByToken(token);
                userElement.setToken(token);
                return userElement;
            } catch (Exception e){
                log.error("通过token获取用户在缓存中的信息失败", e);
                throw e;
            }
        }
        return userElement;
    }
}
